<?php
/*
 * Delete a recipe.
 */

// authenticate user first
F3::call('authentication.php');
if (F3::exists('auth_error'))
{
  // authentication failed
  return;
}

if (!F3::exists("PARAMS['recipe_id']")):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Need a recipe id.");
	echo json_encode($err);
	return;
endif;

// get user ID from session
if(!F3::exists('SESSION.user_id')):
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User is not authenticated.");
	echo json_encode($err);
	return;
endif;
$id = F3::get('SESSION.user_id');

// check admin status
$param = array('1' => $id);
$admin = DB::sql("SELECT id from admin WHERE id=?", $param);
if(count($admin)>0):
	$admin = 1;
else:
	$admin = 0;
endif;

// does recipe exist?
$rid = F3::get("PARAMS['recipe_id']");
$param = array('1'=>$rid);
$result = DB::sql("SELECT author from recipes where rid = ?", $param);
if(count($result)==0):
	//the recipe doesn't exist
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "Recipe does not exist.");
	echo json_encode($err);
	return;
elseif(!$admin && $result[0]['author']!=$id):
	//user does not have authority to delete recipe
	$author = $results[0]['author'];
	header('HTTP/1.1 500 Internal Server Error');
	header("Content-Type: application/json");
	$err = array("error_message" => "User cannot delete recipe.  Not the author. Author: $author");
	echo json_encode($err);
	return;
endif;

// delete recipe
$param = array('1'=>$rid);
DB::sql("delete from recipes where rid = ?",$param);

// success
header('HTTP/1.1 204');
header("Content-Type: application/json");
$response = "success";
echo json_encode($response);
return;
?>
